package com.grm.common.utils;

import com.grm.common.constant.SysConstant;
import com.grm.common.exception.BusinessException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;

@Data
@Component
@Slf4j
public class JwtUtil {
    private static final SecretKey SECURITY_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    @Autowired
    private HttpServletRequest request;

    /**
     * 创建token
     */
    public String createToken(String username, Long userId) {
        JwtBuilder jwtBuilder = Jwts.builder().setSubject(username)  //设置主题 Jwt面向的用户
                .claim("project", "project_base") //自定义属性
                .claim("username", username) //自定义属性
                .claim("userId", userId) //自定义属性
                .claim("uuid", RandomStringUtils.randomAlphanumeric(16))
                .signWith(SignatureAlgorithm.HS256, SECURITY_KEY);//签名,进行**加密
        return jwtBuilder.compact();
    }

    /**
     * 解析token,获取username
     */
    public String getUsername() {
        try {
            String token = request.getHeader(SysConstant.TOKEN);
            Claims body = getClaimsByToken(token);
            return (String) body.get("username");
        } catch (Exception e) {
            log.error("getUsernameByToken exception.", e);
            throw new BusinessException(4013, "token非法!");
        }
    }

    /**
     * 解析token,获取userId
     */
    public Long getUserId() {
        try {
            String token = request.getHeader(SysConstant.TOKEN);
            Claims body = getClaimsByToken(token);
            return Long.parseLong(String.valueOf(body.get("userId")));
        } catch (Exception e) {
            log.error("getUserIdByToken exception.", e);
            throw new BusinessException("token非法!");
        }
    }

    /**
     * 解析token,获取Claims
     */
    private Claims getClaimsByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECURITY_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            log.error("Token解析失败", e);
            throw new BusinessException("token非法!");
        }
    }
}
